<template>
  <div>
    <el-card>
      <div slot="header" style="font-size: 20px; font-weight: 600">
        用户管理
      </div>
      <div class="sift_wrapper">
        <el-form :model="queryInfo" label-width="80px" inline>
          <el-form-item label="用户邮箱" :label-width="formLabelWidth">
            <div>
              <el-input
                style="width: 400px"
                placeholder="请输入用户邮箱"
                v-model="queryInfo.username"
                @change="searchUser($event)"
              >
                <template
                  slot="suffix"
                  class="suffix_input"
                  style="padding-right: 20px; font-size: 20px"
                  >@lunangangster.store</template
                >
              </el-input>
            </div>
          </el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchUser()"
            id="queryBtn"
          >
            查询
          </el-button>
        </el-form>
      </div>
      <el-table
        :data="userList"
        border
        stripe
        v-loading="tableLoading"
        element-loading-text="正在加载用户列表..."
      >
        <el-table-column label="序号" align="center" width="50px">
          <template scope="scope">
            <span>{{
              (currentPage - 1) * currentPageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="用户名"
          prop="username"
        ></el-table-column>
        <el-table-column align="center" label="用户类型" prop="type">
          <template slot-scope="scope">
            <span v-if="scope.row.level == 0">管理员</span>
            <span v-else-if="scope.row.level == 1">普通用户</span>
            <span v-else-if="scope.row.level == -1">已禁用用户</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="260px">
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                justify-content: space-evenly;
                align-items: center;
              "
            >
              <div>
                <el-tooltip
                  :content="scope.row.status ? '禁用用户' : '启用用户'"
                >
                  <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="
                      scope.row.status = !scope.row.status;
                      levelChange(scope.row, $event);
                    "
                    :disabled="scope.row.level == 0"
                  >
                  </el-switch>
                </el-tooltip>
              </div>
              <!-- 编辑按钮 -->
              <div>
                <el-button
                  type="danger"
                  size="mini"
                  :disabled="scope.row.level == 0"
                  @click="deleteUser(scope.row)"
                >
                  删除用户
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pagination_wrapper" style="margin-top: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="currentPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      queryInfo: { username: "" },
      currentPage: 1,
      currentPageSize: 10,
      total: 0,
      newDialogFlag: false,
      editDialogFlag: false,
      levelChangeDialogFlag: false,
      formLabelWidth: "120",
      tableLoading: false,
      nowRowClubInfo: { clubName: "" },
      formRules: {
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }]
      },
      nowClubType: ""
    };
  },
  created() {
    // if (Number(window.sessionStorage.getItem("UT")) !== 30000) {
    //   return this.$router.push("/");
    // }
    this.getAllUsers();
  },
  methods: {
    async getAllUsers() {
      if (this.queryInfo.username != "") return this.searchUser();
      this.tableLoading = true;
      const { data: res } = await this.$http({
        url: `/smtpmail/user/all/${this.currentPage}/${this.currentPageSize}`,
        method: "get"
      });
      if (res.code === 20000) {
        console.log(res);
        res.data.page.records.forEach((item) => {
          if (item.level == 1 || item.level == 0) {
            item.status = true;
          } else {
            item.status = false;
          }
        });
        this.userList = res.data.page.records;
        console.log(this.userList);
        this.total = res.data.page.total;
      }
      this.tableLoading = false;
    },

    /**
     * @description 搜索用户
     */
    async searchUser(username) {
      if (username == "") return this.getAllUsers();
      const { data: res } = await this.$http({
        url: `/smtpmail/user/search/${this.currentPage}/${this.currentPageSize}`,
        method: "get",
        params: {
          username: this.queryInfo.username
        }
      });
      if (res.code === 20000) {
        res.data.page.records.forEach((item) => {
          if (item.level == 1 || item.level == 0) {
            item.status = true;
          } else {
            item.status = false;
          }
        });
        this.userList = res.data.page.records;
        this.total = res.data.page.total;
        this.currentPage = res.data.page.current;
      }
    },

    handleSizeChange(newSize) {
      this.currentPageSize = newSize;
      this.getAllUsers();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getAllUsers();
    },

    async getNowRowInfo(row) {
      this.nowRowClubInfo = JSON.parse(JSON.stringify(row));
    },
    /**
     * @description 删除用户
     */
    async deleteUser(nowRowUserInfo) {
      const confirmRes = await this.$confirm(
        "此操作将修改该用户信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch((err) => err);
      if (confirmRes !== "confirm") {
        return this.$message.info("已取消修改");
      }
      console.log(nowRowUserInfo.username);
      const { data: res } = await this.$http({
        url: "smtpmail/user",
        method: "delete",
        data: [nowRowUserInfo.username]
      });
      console.log(res);
      if (res.code === 20000) {
        this.getAllUsers();
        this.$message.succes("删除成功!");
      } else {
        this.$message.error("删除失败!");
      }
    },

    modifyClub() {
      this.$refs.formRules.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请检查表单信息！");
        }
        // 弹框询问用户是否修改数据
        const confirmRes = await this.$confirm(
          "此操作将修改该用户信息, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).catch((err) => err);
        if (confirmRes !== "confirm") {
          return this.$message.info("已取消修改");
        }
        let form = {
          id: this.nowRowClubInfo.id,
          name: this.nowRowClubInfo.name
        };
        const { data: res } = await this.$http({
          url: `boot/club`,
          method: "put",
          params: form
        });
        if (res.code === 20000) {
          await this.getAllUsers();
          this.editDialogFlag = false;
          return this.$message.success("修改用户信息成功！");
        } else {
          return this.$message.error("修改用户信息失败！");
        }
      });
    },

    getNewId(evt) {
      if (!evt) return this.$message.error("请选择用户！");
      this.nowClubType = evt[0];
      this.getAllUsers();
    },

    /**
     *@description 启禁用用户
     */
    async levelChange(nowRowUserInfo, newLevel) {
      console.log(newLevel);
      const confirmRes = await this.$confirm(
        "此操作将更改当前用户状态, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch((err) => err);
      console.log(confirmRes);
      if (confirmRes !== "confirm") {
        return this.$message.info("已取消修改");
      }
      try {
        if (newLevel) {
          const { data: res } = await this.$http.post("/smtpmail/user/able", [
            nowRowUserInfo.username
          ]);
          if (res.code === 20000) {
            nowRowUserInfo.level = 1;
            nowRowUserInfo.status = newLevel;
            this.$message.success("修改成功!");
          } else {
            this.$message.error("修改失败!");
          }
        } else {
          const { data: res } = await this.$http.post(
            "/smtpmail/user/disable",
            [nowRowUserInfo.username]
          );
          console.log(res);
          if (res.code === 20000) {
            nowRowUserInfo.level = -1;
            nowRowUserInfo.status = newLevel;
            this.$message.success("修改成功!");
          } else {
            this.$message.error("修改失败!");
          }
        }
      } catch (error) {
        this.$message.error("修改失败!");
      }
    }
  }
};
</script>

<style>
.el-input__suffix-inner {
  margin-right: 10px;
  font-size: 15px;
}
</style>